<template>
    <div class="app-container">

        <SearchContent :queryParams="queryParams" @query="handleQuery" @reset="resetQuery">
            <el-col :span="6">
                <el-form-item label="消息类型:" prop="messageType">
                    <el-select v-model="queryParams.messageType" clearable>
                        <el-option :label="item.dictLabel" :value="item.dictSort"
                            v-for="(item, index) in busFlowTypeList" :key="index"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="消息通知名称:" prop="title">
                    <el-input v-model="queryParams.title" clearable placeholder="请输入消息通知"></el-input>
                </el-form-item>
            </el-col>
        </SearchContent>

        <div class="card-wrap paddingAll20" :model="queryParams" label-width="86px">
            <table-page :loading="loading" :dataList="dataList" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @setSizeCurrent="getList" border>
                <!-- 操作插槽 -->
                <template slot="tableColAc">
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="60px">
                        <template v-slot="{ row }">
                                <e-button size="mini" type="text" @click="handleOperate(1, row)"
                                    v-hasPermi="['messageManagement:notification:edit']">编辑
                                </e-button>
                                <e-button size="mini" type="text" @click="handleOperate(4, row)"
                                    v-hasPermi="['messageManagement:notification:see']">查看
                                </e-button>
                        </template>
                    </el-table-column>
                </template>
                <!-- 普通列插槽 -->
                <template slot="tableCol">
                    <el-table-column label="消息通知" align="center" prop="title" min-width="120px" show-overflow-tooltip />
                    <el-table-column label="消息类型" align="center" prop="messageType" min-width="120px"
                        show-overflow-tooltip>
                        <template v-slot="{ row }">
                            <dict-tag :options="dict.type.message_type" :value="row.messageType" />
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" align="center" prop="status" min-width="120px" show-overflow-tooltip>
                        <template v-slot="{ row }">
                            <span v-if="row.status == 0">启用</span>
                            <span v-if="row.status == 1">停用</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="更新时间" align="center" prop="updateTime" min-width="120px"
                        show-overflow-tooltip />
                </template>
            </table-page> 

        </div>
        <el-dialog :title="title" :visible.sync="open" append-to-body class="form-dialog" width="45%" :destroy-on-close="true">
            <el-form ref="form" :rules="rules" :model="form" label-width="140px" @submit.native.prevent>

                <el-row>
                    <el-col :span="20">
                        <el-form-item label="消息通知:" prop="title">
                            <el-input maxlength="50" disabled v-model="form.title" clearable
                                placeholder="请输入标签名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="消息类型:" prop="messageType">
                            <el-input maxlength="50" disabled v-model="form.messageType" clearable
                                placeholder="请输入标签名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="相关参数:" prop="customerDictName" v-if="title == '编辑'">
                            <span v-for="(item, index) in form.messageParamList" :key="index">
                                <el-tag class='parameter' @click="insert(item.paramValue)">{{ item.paramName }}</el-tag>
                            </span>
                        </el-form-item>
                        <el-form-item label="相关参数:" prop="customerDictName" v-else>
                            <span v-for="(item, index) in form.messageParamList" :key="index">
                                <el-tag class='parameter'>{{ item.paramName }}</el-tag>
                            </span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="通知内容:" prop="content">
                            <el-input v-model="form.content" type="textarea" maxlength="500" :rows="2" clearable
                                placeholder="请输入标签描述" :disabled='status' id="textarea" ref="singleText" @blur="getSelectionStart"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="通知人员:" prop="receiveId">
                            <span class="noticeColor">已添加(</span>
                            <span class="noticeColor">{{ noticeNum }}</span>
                            <span class="notice noticeColor">)人</span>
                            <span class="notice noticeColor" @click="addNotice" v-if="isNew">添加通知人员</span>
                            <span class="notice noticeColor" @click="addNotice" v-if="!isNew">查看通知人员</span>
                            <span class="notice noticeColor" @click="clearNotice" v-if="isNew">清空</span>
                        </el-form-item>
                    </el-col>
                    <el-col :span="20" v-if="form.messageType !=='审批通知' && form.messageType !=='审批结果通知'">
                        <el-form-item label="是否开启客户通知:" prop="flag" >
                            <el-switch v-model="form.flag" :disabled='status'></el-switch>
                        </el-form-item>
                    </el-col> 
                    <el-col :span="20">
                        <el-form-item label="通知方式:" prop="pushType">
                            <el-checkbox-group v-model="form.pushType" :disabled='status'>
                                <el-checkbox label=1 name="1">短信</el-checkbox>
                                <el-checkbox label=2 name="2">邮件</el-checkbox>
                                <el-checkbox label=3 name="3">站内信</el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="20">
                        <el-form-item label="状态:" prop="status">
                            <el-radio-group v-model="form.status" :disabled='status'>
                                <el-radio :label=0>启用</el-radio>
                                <el-radio :label=1>停用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer">
                <el-button @click="cancel">{{ isNew ? '取消' : '关闭' }}</el-button>
                <el-button :loading="buttonLoading" type="primary" @click="submitForm" v-if="isNew">确 定</el-button>
            </div>
            <el-dialog
                width="60%"
                title="通知人员"
                :visible.sync="noticeState"
                :destroy-on-close="true"
                @close="noticeCancel"
                append-to-body>
                    <div v-if="noticSatus">
                        <NoticeModle :info="noticeInfo" @valueChanged="handleValueChange" v-if="isNew" />
                        <NoticeSeeModle :info="noticeInfo" v-if="!isNew"/>
                    </div>
                   
                <div slot="footer" v-if="isNew">
                    <el-button @click="noticeCancel">取消</el-button>
                    <el-button :loading="buttonLoading" type="primary" @click="noticeSubmitForm" >确 定</el-button>
                </div>
            </el-dialog>
        </el-dialog>
    </div>
</template>

<script>
import SearchContent from "@/components/SearchContent/index.vue";
import * as apis from "@/api/messageManagement/index.js";
import NoticeModle from "@/views/messageManagement/notification/notice.vue"
import NoticeSeeModle from "@/views/messageManagement/notification/noticeSee.vue"
import { watch } from "vue-demi";
export default {
    name: "MessageNotification",
    components: {
        SearchContent,
        NoticeModle,
        NoticeSeeModle,
    },
    dicts: ['business_type', 'purchase_source', 'in_storage_status', 'in_storage_source', 'message_type'],
    data() {
        return {
            // 遮罩层
            loading: false,
            retutnCarTimes: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                title: null,
            },
            total: 0,
            dataList: [],
            open: false,
            title: "",
            rules: {
                title:[
                    { required: true, message: "请输入消息通知", trigger: "blur" },
                ],
                messageType:[
                    { required: true, message: "请选择消息类型", trigger: "blur" },
                ],
                content:[
                    { required: true, message: "请输入通知内容", trigger: "blur" },
                ],
                flag:[
                    { required: true, message: "请输选择", trigger: "blur" },
                ],
                pushType:[
                    { required: true, message: "请选择通知方式", trigger: "blur" },
                ],
                status:[
                    { required: true, message: "请选择状态", trigger: "blur" },
                ]
            },
            form: {
                list: [
                    {
                        id: 1,
                        name: '申请编码'
                    },
                    {
                        id: 2,
                        name: '审核类型'
                    },
                ],
                resource: "停用",
                content: '',
                pushType: [1],
                status: 1,
                flag: false,
                messageType:null,
            },
            isNew: true,
            buttonLoading: false,
            status: false,
            busFlowTypeList: [],
            noticeNum:0,
            noticeState:false,
            noticeInfo:[], // 选中通知人员
            noticSatus:false,
            startPostion:null,
            endPostion:null,
        };
    },
    mounted() {
        this.getList()
    },
    async created() {
        this.busFlowTypeList = await this._getDicts("message_type");
    },
    activated() {
        this.handleQuery()
    },
    watch:{
        noticeInfo:{
            deep:true,
            handler(val){
                this.noticeInfo = val
            }
        }
    },
    methods: {
        //选中通知人员
        handleValueChange(val){
           this.noticeInfo = val
        },
        //选择通知人员弹框-关闭
        noticeCancel(){
            this.noticeState = false
            this.noticSatus =false
        },
        //选择通知人员弹框-关闭
        noticeSubmitForm(){
            this.noticeState = false
            this.noticSatus =false
            let list =[]
            if(this.noticeInfo){
                this.noticeInfo.map((res)=>{
                    if(res.userId){
                        list.push(res.userId)
                    }else{
                        list.push(res)
                    }   
                })
                this.noticeNum = this.noticeInfo?.length
            }
            this.$set(this.form,'receiveId',list.join(','))
            this.noticeInfo = []
        },
        //点击添加通知人员
        addNotice(){
            this.noticSatus = true
            this.noticeInfo = []
            this.noticeInfo = this.form.receiveId?.split(',')
            this.noticeState = true  
        },
        // 清空通知人员
        clearNotice(){
            this.noticeNum = 0
            this.noticeInfo = [],
            this.$set(this.form,'receiveId','')
        },
        getSelectionStart(e){  
            this.startPostion=e.srcElement.selectionStart
            this.endPostion=e.srcElement.selectionEnd
        },
        // 焦点处填入数据
        async insert(myValue) {
            const myField = this.$refs.singleText;
            if (this.startPostion || this.startPostion !== 0) {
                var startPos = this.startPostion;
                var endPos = this.endPostion;
                this.$set(this.form, 'content', myField.value.substring(0, startPos) + `{${myValue}}` + myField.value.substring(endPos, myField?.value?.length))
                await this.$nextTick();
                myField.focus();
                // myField.setSelectionRange(
                //     endPos + myValue?.length,
                //     endPos + myValue?.length
                // );
            } else {
                this.$set(this.form, 'content', this.form.content += `{${myValue}}`)
            }
        },
        submitForm() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    const param = {
                        id: this.form?.id,
                        content: this.form?.content,
                        receiveId: this.form?.receiveId,
                        receiveName: '',
                        flag: this.form?.flag===true ? 1 : 0,
                        status: this.form?.status,
                        pushType: this.form?.pushType?.toString(),
                    }
                    apis.messageNoticeUpdate(param).then((res) => {
                        if (res.code == 200) {
                            this.open = false
                            this.$message.success('编辑成功')
                        }
                    })
                } 
                });
           
        },
        cancel() {
            this.open = false
        },
        /** 查询列表 */
        getList() {
            this.loading = true;
            apis.messageNoticeList(this.queryParams).then(res => {
                this.dataList = res.rows;
                this.total = res.total;
            }).finally(() => {
                this.loading = false
            })
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },

        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                vinNo: null,
            },
                this.getList();
        },


        handleOperate(type, row) {
            this.open = true
            if (type == 1) {
                this.title = '编辑'
                this.isNew = true
                this.status = false
            } else {
                this.title = '查看'
                this.isNew = false
                this.status = true
            }
            apis.messageCountDetail(row.id).then((res) => {
                if (res.code == 200) {
                    if (res?.data?.pushType) {
                        res.data.pushType = res.data?.pushType?.split(',')
                    } else {
                        res.data.pushType = []
                    }
                    this.busFlowTypeList?.map((item) => {
                        if (item.dictSort == res.data.messageType) {
                            res.data.messageType = item.dictLabel

                        }
                        
                        this.form = res.data
                        if(res.data.flag==0){
                            this.$set(this.form,'flag',false)
                        }else{
                            this.$set(this.form,'flag',true)
                        }
                    })
                    const num = res.data.receiveId?res.data.receiveId.split(','):[]
                     this.noticeNum = num.length
                }
            })
        },


    }
};
</script>
<style scope>
.parameter {
    cursor: pointer;
    margin-right: 5px;
}
.notice{
    margin-right: 15px;
    cursor: pointer;
}
.noticeColor{
    color: blue;
}
</style>
